package com.ysz.cli;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * @ClassName Init
 * @Description TODO
 * @Data 13:50
 * @Version 1.0
 * @Author ysz
 */
public class Init {

    //private static final String CONNECTION_ADDRESS = "192.168.245.128:2181,192.168.245.128:2182,192.168.245.128:2183";
    private static final String CONNECTION_ADDRESS = "192.168.245.128:2188";
    private static final int SESSION_TIME_OUT_MS = 60 * 1000;
    private static final int CONNECTION_TIME_OUT_MS = 5000;
    private static CuratorFramework build;

    static {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(5000, 30);
        build = CuratorFrameworkFactory.builder()
                .retryPolicy(retryPolicy)
                .connectString(CONNECTION_ADDRESS)
                .sessionTimeoutMs(SESSION_TIME_OUT_MS)
                .connectionTimeoutMs(CONNECTION_TIME_OUT_MS)
                .canBeReadOnly(true)
                .authorization("digest", "ysz3:ysz3".getBytes())
                .build();
        build.getConnectionStateListenable().addListener((listener, executor1) -> {
            //CuratorFrameworkImpl
            if (executor1 == ConnectionState.CONNECTED) {
                System.out.println("连接成功！");
            }
        });
        build.start();
    }

    public static CuratorFramework getBuild() {
        return build;
    }
}
